<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="spring cache,redis," />





  <link rel="alternate" href="/atom.xml" title="流水不腐小夏" type="application/atom+xml" />






<meta name="description" content="Spring Cache与Redis结合使用  Spring Cache与Redis结合使用 Redis 创建Spring项目 集成Redis Cache部分代码      前不久做了一个需要查询多，更新少的功能，老司机同事建议用Redis来做缓存，同时结合Spring Cache来做，特来总结下。 RedisRedis 是一个高性能key-value数据库，个人感觉就像java中的Map，不过比">
<meta name="keywords" content="spring cache,redis">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring Cache与Redis结合使用">
<meta property="og:url" content="http://mycommons.cn/2017/11/19/Spring-Cache-Redis/index.html">
<meta property="og:site_name" content="流水不腐小夏">
<meta property="og:description" content="Spring Cache与Redis结合使用  Spring Cache与Redis结合使用 Redis 创建Spring项目 集成Redis Cache部分代码      前不久做了一个需要查询多，更新少的功能，老司机同事建议用Redis来做缓存，同时结合Spring Cache来做，特来总结下。 RedisRedis 是一个高性能key-value数据库，个人感觉就像java中的Map，不过比">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1520343-0681b36a99876f74.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1520343-a53244d3d8035cb8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1520343-bf26e80d9fdabdf2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1520343-a4070880af6988f5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2017-11-19T15:50:33.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring Cache与Redis结合使用">
<meta name="twitter:description" content="Spring Cache与Redis结合使用  Spring Cache与Redis结合使用 Redis 创建Spring项目 集成Redis Cache部分代码      前不久做了一个需要查询多，更新少的功能，老司机同事建议用Redis来做缓存，同时结合Spring Cache来做，特来总结下。 RedisRedis 是一个高性能key-value数据库，个人感觉就像java中的Map，不过比">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/1520343-0681b36a99876f74.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'GRLHBBCD9E',
      apiKey: '759ab3f5c09b132b3ed4842a44c53c45',
      indexName: 'mycommons',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://mycommons.cn/2017/11/19/Spring-Cache-Redis/"/>





  <title>Spring Cache与Redis结合使用 | 流水不腐小夏</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?55458ffca1f60dd283f11b9a7f82b262";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">流水不腐小夏</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">http://mycommons.cn</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  
  <div class="algolia-popup popup search-popup">
    <div class="algolia-search">
      <div class="algolia-search-input-icon">
        <i class="fa fa-search"></i>
      </div>
      <div class="algolia-search-input" id="algolia-search-input"></div>
    </div>

    <div class="algolia-results">
      <div id="algolia-stats"></div>
      <div id="algolia-hits"></div>
      <div id="algolia-pagination" class="algolia-pagination"></div>
    </div>

    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>




    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://mycommons.cn/2017/11/19/Spring-Cache-Redis/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="流水不腐小夏">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="流水不腐小夏">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Spring Cache与Redis结合使用</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-19T23:48:13+08:00">
                2017-11-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/后端开发/" itemprop="url" rel="index">
                    <span itemprop="name">后端开发</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/11/19/Spring-Cache-Redis/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2017/11/19/Spring-Cache-Redis/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Spring-Cache与Redis结合使用"><a href="#Spring-Cache与Redis结合使用" class="headerlink" title="Spring Cache与Redis结合使用"></a>Spring Cache与Redis结合使用</h1><!-- TOC -->
<ul>
<li><a href="#spring-cache与redis结合使用">Spring Cache与Redis结合使用</a><ul>
<li><a href="#redis">Redis</a></li>
<li><a href="#创建spring项目">创建Spring项目</a></li>
<li><a href="#集成redis">集成Redis</a></li>
<li><a href="#cache部分代码">Cache部分代码</a></li>
</ul>
</li>
</ul>
<!-- /TOC -->
<hr>
<p>前不久做了一个需要查询多，更新少的功能，老司机同事建议用Redis来做缓存，同时结合Spring Cache来做，特来总结下。</p>
<h2 id="Redis"><a href="#Redis" class="headerlink" title="Redis"></a>Redis</h2><p>Redis 是一个高性能key-value数据库，个人感觉就像java中的Map，不过比它更加强大。</p>
<p>由于我用的是Mac，下面介绍如何安装Redis。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">brew update</div><div class="line"></div><div class="line">brew install redis</div></pre></td></tr></table></figure>
<p>开启服务</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">brew services start redis</div><div class="line"></div><div class="line">brew services list</div></pre></td></tr></table></figure>
<p>下面是我本机的运行截图</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1520343-0681b36a99876f74.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image"></p>
<h2 id="创建Spring项目"><a href="#创建Spring项目" class="headerlink" title="创建Spring项目"></a>创建Spring项目</h2><p>我这边为了简单方便，直接使用了Spring Boot，直接用IntelJ Idea，需要添加<code>Redis</code>、<code>Cache</code>和<code>Lombok</code>库。</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1520343-a53244d3d8035cb8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image"></p>
<p><img src="http://upload-images.jianshu.io/upload_images/1520343-bf26e80d9fdabdf2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image"></p>
<p><img src="http://upload-images.jianshu.io/upload_images/1520343-a4070880af6988f5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image"></p>
<h2 id="集成Redis"><a href="#集成Redis" class="headerlink" title="集成Redis"></a>集成Redis</h2><p>集成Redis，直接在配置文件配置即可。</p>
<p>application.properties</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">#redis</div><div class="line">spring.redis.host=localhost</div><div class="line">spring.redis.port=6379</div><div class="line">spring.redis.password=</div><div class="line">spring.redis.timeout=0</div></pre></td></tr></table></figure>
<p>然后测试下Redis是否集成功。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Slf</span>4j</div><div class="line"><span class="meta">@RunWith</span>(SpringRunner.class)</div><div class="line"><span class="meta">@SpringBootTest</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringcacheApplicationTests</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    StringRedisTemplate redisTemplate;</div><div class="line"></div><div class="line">    <span class="meta">@Test</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">contextLoads</span><span class="params">()</span> </span>&#123;</div><div class="line">        Assert.assertNotNull(redisTemplate);</div><div class="line"></div><div class="line">        redisTemplate.opsForValue().set(<span class="string">"hello"</span>, <span class="string">"world"</span>);</div><div class="line">        String value = redisTemplate.opsForValue().get(<span class="string">"hello"</span>);</div><div class="line">        log.info(<span class="string">"value = "</span> + value);</div><div class="line"></div><div class="line">        redisTemplate.delete(<span class="string">"hello"</span>);</div><div class="line"></div><div class="line">        value = redisTemplate.opsForValue().get(<span class="string">"hello"</span>);</div><div class="line">        log.info(<span class="string">"value = "</span> + value);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>运行结果如下，如果没有出错，则表示集成功。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">2017-11-19 14:56:10.075  INFO 73896 --- [           main] c.m.s.SpringcacheApplicationTests        : value = world</div><div class="line">2017-11-19 14:56:10.076  INFO 73896 --- [           main] c.m.s.SpringcacheApplicationTests        : value = null</div></pre></td></tr></table></figure>
<h2 id="Cache部分代码"><a href="#Cache部分代码" class="headerlink" title="Cache部分代码"></a>Cache部分代码</h2><p>配置CacheManager，它的实现部分是由RedisCacheManager来实现的，我们先设置缓存时间为3s，超过这个时间，缓存自动失效。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div></pre></td><td class="code"><pre><div class="line">@Configuration</div><div class="line">@EnableCaching</div><div class="line">public class CachingConfig &#123;</div><div class="line"></div><div class="line">    @Bean</div><div class="line">    public CacheManager cacheManager(RedisTemplate redisTemplate) &#123;</div><div class="line">        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);</div><div class="line">        redisCacheManager.setDefaultExpiration(3);</div><div class="line">        return redisCacheManager;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    @Bean</div><div class="line">    public CacheErrorHandler errorHandler() &#123;</div><div class="line">        return new RedisCacheErrorHandler();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    @Slf4j</div><div class="line">    private static class RedisCacheErrorHandler extends SimpleCacheErrorHandler &#123;</div><div class="line"></div><div class="line">        @Override</div><div class="line">        public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) &#123;</div><div class="line">            log.error(&quot;handleCacheGetError key = &#123;&#125;, value = &#123;&#125;&quot;, key, cache);</div><div class="line">            log.error(&quot;cache get error&quot;, exception);</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        @Override</div><div class="line">        public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) &#123;</div><div class="line">            log.error(&quot;handleCachePutError key = &#123;&#125;, value = &#123;&#125;&quot;, key, cache);</div><div class="line">            log.error(&quot;cache put error&quot;, exception);</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        @Override</div><div class="line">        public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) &#123;</div><div class="line">            log.error(&quot;handleCacheEvictError key = &#123;&#125;, value = &#123;&#125;&quot;, key, cache);</div><div class="line">            log.error(&quot;cache evict error&quot;, exception);</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        @Override</div><div class="line">        public void handleCacheClearError(RuntimeException exception, Cache cache) &#123;</div><div class="line">            log.error(&quot;handleCacheClearError value = &#123;&#125;&quot;, cache);</div><div class="line">            log.error(&quot;cache clear error&quot;, exception);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>添加一个简单的实体，然后添加服务接口和实现类。</p>
<p><code>@Data</code>是lombok提供的，可以减少简洁代码。注意实体必须实现<code>Serializable</code>接口。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Data</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">int</span> id;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> String name;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> String email;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserService</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">void</span> <span class="title">addUser</span><span class="params">(User user)</span></span>;</div><div class="line"></div><div class="line">    <span class="function">User <span class="title">findById</span><span class="params">(<span class="keyword">int</span> id)</span></span>;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">void</span> <span class="title">delete</span><span class="params">(<span class="keyword">int</span> id)</span></span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Slf</span>4j</div><div class="line"><span class="meta">@Service</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserServiceImpl</span> <span class="keyword">implements</span> <span class="title">UserService</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Map&lt;Integer, User&gt; db = <span class="keyword">new</span> HashMap&lt;&gt;();</div><div class="line"></div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addUser</span><span class="params">(User user)</span> </span>&#123;</div><div class="line">        log.info(<span class="string">"addUser.user = "</span> + user);</div><div class="line">        db.put(user.getId(), user);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@Cacheable</span>(cacheNames = <span class="string">"user_cache"</span>, key = <span class="string">"#id"</span>)</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">findById</span><span class="params">(<span class="keyword">int</span> id)</span> </span>&#123;</div><div class="line">        log.info(<span class="string">"findById.id = "</span> + id);</div><div class="line"></div><div class="line">        <span class="keyword">return</span> db.get(id);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="meta">@CacheEvict</span>(cacheNames = <span class="string">"user_cache"</span>, key = <span class="string">"#id"</span>)</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">delete</span><span class="params">(<span class="keyword">int</span> id)</span> </span>&#123;</div><div class="line">        log.info(<span class="string">"delete.id = "</span> + id);</div><div class="line"></div><div class="line">        db.remove(id);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>上面<code>Cacheable</code>和<code>CacheEvict</code>就是Spring Cache提供的注解。具体说明如下。</p>
<ul>
<li><p>@Cacheable 作用和配置方法</p>
<ul>
<li><p>value、cacheNames<br>缓存的名称，在 spring 配置文件中定义，必须指定至少一个<br>例如: @Cacheable(value=”mycache”) @Cacheable(value={”cache1”,”cache2”}</p>
</li>
<li><p>key<br>缓存的 key，可以为空，如果指定要按照 SpEL 表达式编写，如果不指定，则缺省按照方法的所有参数进行组合<br>例如: @Cacheable(value=”testcache”,key=”#userName”)</p>
</li>
<li><p>condition<br>缓存的条件，可以为空，使用 SpEL 编写，返回 true 或者 false，只有为 true 才进行缓存<br>例如：@Cacheable(value=”testcache”,condition=”#userName.length()&gt;2”)</p>
</li>
</ul>
</li>
<li><p>@CacheEvict 作用和配置方法</p>
<ul>
<li><p>value<br>缓存的名称，在 spring 配置文件中定义，必须指定至少一个<br>例如: @CacheEvict(value=”my cache”)</p>
</li>
<li><p>key<br>缓存的 key，可以为空，如果指定要按照 SpEL 表达式编写，如果不指定，则缺省按照方法的所有参数进行组合<br>例如: @CacheEvict(value=”testcache”,key=”#userName”)</p>
</li>
<li><p>condition<br>缓存的条件，可以为空，使用 SpEL 编写，返回 true 或者 false，只有为 true 才进行缓存<br>例如: @CacheEvict(value=”testcache”,condition=”#userName.length()&gt;2”)</p>
</li>
<li><p>allEntries<br>是否清空所有缓存内容，缺省为 false，如果指定为 true，则方法调用后将立即清空所有缓存<br>例如: @CachEvict(value=”testcache”,allEntries=true)</p>
</li>
<li><p>beforeInvocation<br>是否在方法执行前就清空，缺省为 false，如果指定为 true，则在方法还没有执行的时候就清空缓存，缺省情况下，如果方法执行抛出异常，则不会清空缓存<br>例如: @CachEvict(value=”testcache”，beforeInvocation=true)</p>
</li>
</ul>
</li>
</ul>
<p>测试用例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Slf</span>4j</div><div class="line"><span class="meta">@RunWith</span>(SpringRunner.class)</div><div class="line"><span class="meta">@SpringBootTest</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CacheTest</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="meta">@Autowired</span></div><div class="line">    UserService userService;</div><div class="line"></div><div class="line">    <span class="meta">@Test</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">contextLoads</span><span class="params">()</span> </span>&#123;</div><div class="line">        Assert.assertNotNull(userService);</div><div class="line"></div><div class="line">        <span class="comment">// 创建一个实体</span></div><div class="line">        User user = <span class="keyword">new</span> User();</div><div class="line">        user.setId(<span class="number">100</span>);</div><div class="line">        user.setName(<span class="string">"admin"</span>);</div><div class="line">        user.setEmail(<span class="string">"admin@123.com"</span>);</div><div class="line"></div><div class="line">        <span class="comment">// 添加一个</span></div><div class="line">        userService.addUser(user);</div><div class="line"></div><div class="line">        <span class="comment">// 根据Id查询</span></div><div class="line">        log.info(<span class="string">"user1 = "</span> + userService.findById(<span class="number">100</span>));</div><div class="line">        sleep(<span class="number">1</span>);</div><div class="line">        <span class="comment">// 等1s再次查询</span></div><div class="line">        log.info(<span class="string">"user2 = "</span> + userService.findById(<span class="number">100</span>));</div><div class="line">        sleep(<span class="number">5</span>);</div><div class="line">        <span class="comment">// 等5s再次查询</span></div><div class="line">        log.info(<span class="string">"user3 = "</span> + userService.findById(<span class="number">100</span>));</div><div class="line"></div><div class="line">        <span class="comment">// 添加一个</span></div><div class="line">        userService.addUser(user);</div><div class="line">        <span class="comment">// 根据Id查询</span></div><div class="line">        log.info(<span class="string">"user4 = "</span> + userService.findById(<span class="number">100</span>));</div><div class="line">        <span class="comment">// 删除</span></div><div class="line">        userService.delete(<span class="number">100</span>);</div><div class="line">        <span class="comment">// 根据Id查询</span></div><div class="line">        log.info(<span class="string">"user5 = "</span> + userService.findById(<span class="number">100</span>));</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">sleep</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            Thread.sleep(i * <span class="number">1000</span>);</div><div class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>测试结果</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">2017-11-19 15:08:35.732  INFO 76558 --- [           main] c.m.s.service.impl.UserServiceImpl       : addUser.user = User(id=100, name=admin, email=admin@123.com)</div><div class="line">2017-11-19 15:08:35.921  INFO 76558 --- [           main] c.m.s.service.impl.UserServiceImpl       : findById.id = 100</div><div class="line">2017-11-19 15:08:35.951  INFO 76558 --- [           main] cn.mycommons.springcache.CacheTest       : user1 = User(id=100, name=admin, email=admin@123.com)</div><div class="line">2017-11-19 15:08:37.016  INFO 76558 --- [           main] cn.mycommons.springcache.CacheTest       : user2 = User(id=100, name=admin, email=admin@123.com)</div><div class="line">2017-11-19 15:08:42.019  INFO 76558 --- [           main] c.m.s.service.impl.UserServiceImpl       : findById.id = 100</div><div class="line">2017-11-19 15:08:42.021  INFO 76558 --- [           main] cn.mycommons.springcache.CacheTest       : user3 = User(id=100, name=admin, email=admin@123.com)</div><div class="line">2017-11-19 15:08:42.021  INFO 76558 --- [           main] c.m.s.service.impl.UserServiceImpl       : addUser.user = User(id=100, name=admin, email=admin@123.com)</div><div class="line">2017-11-19 15:08:42.022  INFO 76558 --- [           main] cn.mycommons.springcache.CacheTest       : user4 = User(id=100, name=admin, email=admin@123.com)</div><div class="line">2017-11-19 15:08:42.023  INFO 76558 --- [           main] c.m.s.service.impl.UserServiceImpl       : delete.id = 100</div><div class="line">2017-11-19 15:08:42.025  INFO 76558 --- [           main] c.m.s.service.impl.UserServiceImpl       : findById.id = 100</div><div class="line">2017-11-19 15:08:42.025  INFO 76558 --- [           main] cn.mycommons.springcache.CacheTest       : user5 = null</div></pre></td></tr></table></figure>
<p>从结果来看，添加一个数据后，第一次，查询是从UserServiceImpl中获取，再次查询，则没有直接调用UserServiceImpl，直接返回了缓存结果。</p>
<p>当超过缓存时间后，再次去查询，我们这边设置缓存时间为3s，等待5s后，再次查询，发现又从UserServiceImpl中获取数据。</p>
<p>当我们主动调用删除记录，同时同步清楚缓存数据后，发现查询是没有数据的。说明删除和清楚缓存操作实现了同步。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat_pay.jpeg" alt="流水不腐小夏 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpeg" alt="流水不腐小夏 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/spring-cache/" rel="tag"># spring cache</a>
          
            <a href="/tags/redis/" rel="tag"># redis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/10/25/Android-RePlugin/" rel="next" title="是时候来一波Android插件化了">
                <i class="fa fa-chevron-left"></i> 是时候来一波Android插件化了
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/11/26/SpringBoot-Kafka/" rel="prev" title="Spring Boot集成Kafka">
                Spring Boot集成Kafka <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpeg"
                alt="流水不腐小夏" />
            
              <p class="site-author-name" itemprop="name">流水不腐小夏</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">31</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">55</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/LiushuiXiaoxia" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-GitHub"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://www.jianshu.com/u/58771f980bac" target="_blank" title="简书">
                    
                      <i class="fa fa-fw fa-简书"></i>简书</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="http://blog.csdn.net/guijiaoba" target="_blank" title="CSDN">
                    
                      <i class="fa fa-fw fa-CSDN"></i>CSDN</a>
                </span>
              
            
          </div>

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Spring-Cache与Redis结合使用"><span class="nav-number">1.</span> <span class="nav-text">Spring Cache与Redis结合使用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Redis"><span class="nav-number">1.1.</span> <span class="nav-text">Redis</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建Spring项目"><span class="nav-number">1.2.</span> <span class="nav-text">创建Spring项目</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#集成Redis"><span class="nav-number">1.3.</span> <span class="nav-text">集成Redis</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Cache部分代码"><span class="nav-number">1.4.</span> <span class="nav-text">Cache部分代码</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">流水不腐小夏</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.3</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  

  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  

    
      <script id="dsq-count-scr" src="https://mycommons-cn.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://mycommons.cn/2017/11/19/Spring-Cache-Redis/';
          this.page.identifier = '2017/11/19/Spring-Cache-Redis/';
          this.page.title = 'Spring Cache与Redis结合使用';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://mycommons-cn.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  




  
  
  
  <link rel="stylesheet" href="/lib/algolia-instant-search/instantsearch.min.css">

  
  
  <script src="/lib/algolia-instant-search/instantsearch.min.js"></script>
  

  <script src="/js/src/algolia-search.js?v=5.1.3"></script>



  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
